<?php

namespace App\Admin\Actions\Tree;

use App\Models\Open\SysAccountMenu;
use Dcat\Admin\Actions\Response;
use Dcat\Admin\Traits\HasPermissions;
use Dcat\Admin\Tree\AbstractTool;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class SyncSysAccountMenu extends AbstractTool
{
    /**
     * @return string
     */
	protected $title = '同步';

	private $sysAccount;

    /**
     * Handle the action request.
     *
     * @param Request $request
     *
     * @return Response
     */
    public function handle(Request $request)
    {
        $id = $this->getKey();
        $saMenus = SysAccountMenu::where('sys_account_id', $id)->where('parent_id', 0)->get();
        $buttons = $this->getMenus($saMenus);
        $wechatApp = resolve('wechatApp', ['sysId'=>$id]);
        $wechatApp->menu->create($buttons);
        return $this->response()
            ->success('同步菜单成功');
    }

    private function getMenus($menus)
    {
        $res = [];
        foreach ($menus as $menu) {
            if($menu->childs->count() != 0) {
                $res[] = [
                    'name'=>$menu->title,
                    'sub_button'=>$this->getMenus($menu->childs),
                ];
            } else if($menu->type == 'view') {
                $res[] = [
                    'type'=>'view',
                    'name'=>$menu->title,
                    'url'=>$menu->url,
                ];
            } else if($menu->type == 'miniprogram') {
                $res[] = [
                    'type'=>'miniprogram',
                    'name'=>$menu->title,
                    'url'=>$menu->bakurl,
                    'appid'=>$menu->appid,
                    'pagepath'=>$menu->pagepath,
                ];
            } else if($menu->type == 'click') {
                $res[] = [
                    'type'=>'click',
                    'name'=>$menu->title,
                    'key'=>$menu->key,
                ];
            }
        }
        return $res;
    }

    /**
     * @return string|void
     */
    protected function href()
    {
//        dump($this->parent->sysAccount);
//        return admin_url('auth/users');
    }

    /**
	 * @return string|array|void
	 */
	public function confirm()
	{
		// return ['Confirm?', 'contents'];
	}

    /**
     * @param Model|Authenticatable|HasPermissions|null $user
     *
     * @return bool
     */
    protected function authorize($user): bool
    {
        return true;
    }
}
